#include <QDebug>
#include "sessionitem.h"
#include "tcpsession.h"

SessionItem::SessionItem(std::shared_ptr<TcpSession> &session)
{
    m_Session = session;

    //QString ss = QString("%1:%2").arg(session.get()->getIP()).arg(session.get()->getPort());
    m_IpPortStr = session->getIPPort();

    connect(this->m_Session.get(), &TcpSession::SignalRead, this, &SessionItem::SlotRead);
    connect(this->m_Session.get(), &TcpSession::disconnected, this, &SessionItem::SlotDisconnect);
    connect(this->m_Session.get(), &TcpSession::connected, this, &SessionItem::SignalConnected);
}

SessionItem::~SessionItem()
{
    qDebug() << "SessionItem::~SessionItem";
    if(m_Session == nullptr) return;

    disconnect(this->m_Session.get(), &TcpSession::SignalRead, this, &SessionItem::SlotRead);
    disconnect(this->m_Session.get(), &TcpSession::disconnected, this, &SessionItem::SlotDisconnect);
    disconnect(this->m_Session.get(), &TcpSession::connected, this, &SessionItem::SignalConnected);

    qDebug() << m_IpPortStr << " shared(SessionItem)" << m_Session.use_count();

    m_Session = nullptr;
    m_IpPortStr = "";
}

void SessionItem::Write(const char* buf, size_t buf_size)
{
    if(m_Session) m_Session->write(buf, buf_size);
}
void SessionItem::Write(const QByteArray& data)
{
    if(m_Session) m_Session->write(data);
}

void SessionItem::Connect(const QString &addr, quint16 port)
{
    if(m_Session) m_Session->connectToHost(addr, port);
}

//slots
void SessionItem::SlotRead(const QByteArray& data)
{
    emit SignalRead(m_IpPortStr, data);
}

void SessionItem::SlotDisconnect()
{
    emit SignalDisconnected(m_IpPortStr);
}

QString& SessionItem::GetSessionStr()
{
    return m_IpPortStr;
}
